<template>
    <div class="jianzhan-content">
        <Crumb name="寄售合同/Consignment"></Crumb>
        <div class="content">
            <el-button type="primary" size="small" class="input" icon="el-icon-plus" @click="openAdd"
                       v-if="urlAvailible('shanqi-contract-operate')">添加寄售合同
            </el-button>
            <div class="total" style="float: right;margin-right: 30px;">总金额: {{total}}</div>
            <div class="table-wrapper">
                <el-table
                        :data="consignmentList.filter(item=>item.contractNumber.includes(key))"
                        border
                        stripe
                        row-key="id"
                        @expand-change="getPartDetail"
                        empty-text="暂无数据/NO Data"
                        style="width: 100%">

                    <el-table-column
                            type="expand"
                    >
                        <template slot-scope="scope">
                            <el-table
                                    :data="scope.row.partList"
                                    stripe
                                    border
                                    height="500px"
                                    style="width:95%">
                                <el-table-column
                                        prop="partsNumber"
                                        label="配件编号"
                                >
                                </el-table-column>
                                <el-table-column
                                        prop="denomination"
                                        label="中文"
                                        width="180">
                                </el-table-column>
                                <el-table-column
                                        prop="designation"
                                        label="英文">
                                </el-table-column>
                                <el-table-column
                                        prop="quantity"
                                        label="数量">
                                </el-table-column>
                                <el-table-column
                                        prop="unit"
                                        label="单位">
                                </el-table-column>
                                <el-table-column
                                        prop="salesUnitPrice"
                                        label="单价">
                                </el-table-column>
                                <el-table-column
                                        prop="totalPrice"
                                        label="总价">
                                </el-table-column>
                                <el-table-column
                                        prop="remarks"
                                        label="备注">
                                </el-table-column>
                            </el-table>
                        </template>
                    </el-table-column>
                    <el-table-column
                            type="index"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="contractNumber"
                            label="合同号/Contract No"
                            width="180">
                    </el-table-column>
                    <el-table-column
                            sortable
                            prop="contractDateStr"
                            label="日期/Date"
                            width="180">
                    </el-table-column>
                    <el-table-column
                            :filters="[
                                {
                                    text:'WEDA',
                                    value:'WEDA',
                                },
                                {
                                    text:'MOROWALI',
                                    value:'MOROWALI',
                                },{
                                    text:'MKS',
                                    value:'MKS',
                                }
                            ]"
                            :filter-method="filterCustomer"
                            prop="customer"
                            label="客户/Customer">
                    </el-table-column>
                    <el-table-column
                            prop="totalPrice"
                            label="总金额/Total Price">
                    </el-table-column>
                    <el-table-column
                            :filter-method="filterStatus"
                            :filters="[
                                {
                                    text:'Delivered',
                                    value:0
                                },
                                 {
                                    text:'Not All delivered',
                                    value:1
                                },
                                {
                                    text:'No Part',
                                    value:2
                                }
                            ]"
                            prop="remainingOrNot"
                            label="Delivery Status">
                        <template slot-scope="scope">
                            <span v-if="scope.row.remainingOrNot===1"
                                  @click="showUnDelivery(scope.row)"
                                  style="cursor: pointer;text-decoration: underline"
                            >Not All delivered</span>
                            <span v-else-if="scope.row.remainingOrNot===2">No Part</span>
                            <span v-else>Delivered</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="marks"
                            label="备注/Remark">
                    </el-table-column>

                    <el-table-column width="350px">
                        <template slot="header" slot-scope="scope">
                            <el-input v-model="key" class="my-input" placeholder="查询合同号" size="small"
                                      prefix-icon="el-icon-search"></el-input>
                        </template>
                        <template slot-scope="scope">
                            <el-button type="primary" size="small" @click="openEdit(scope.row)" icon="el-icon-edit">
                                Edit
                            </el-button>
                            <el-button type="primary" size="small" @click="getConsignmentTime(scope.row)" icon="el-icon-edit">
                                Consignment Time
                            </el-button>

                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <el-dialog
                title="寄售合同/Consignment"
                :visible.sync="dialogVisible"
                width="80%"
        >
            <el-form ref="form" :model="consignment" :rules="rule" label-width="150px" inline style="text-align: left">
                <el-form-item label="合同号/Contract No" prop="contractNumber">
                    <el-input v-model="consignment.contractNumber" placeholder="Contract Number"
                              size="small"></el-input>
                </el-form-item>
                <el-form-item label="日期/Date" prop="contractDateStr">
                    <el-date-picker value-format="yyyy-MM-dd" size="small" v-model="consignment.contractDateStr"
                                    placeholder="Please select date"></el-date-picker>
                </el-form-item>
                <el-form-item label="客户/Customer">
                    <el-select v-model="consignment.customer" placeholder="Customer" size="small">
                        <el-option label="MOROWALI" value="MOROWALI"></el-option>
                        <el-option label="WEDA" value="WEDA"></el-option>
                        <el-option label="MKS" value="MKS"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="总价格/Total Price">
                    <el-currency-input v-model="consignment.totalPrice" placeholder="Total price"
                                       size="small"></el-currency-input>
                </el-form-item>
                <!--<el-form-item label="发运方式">-->
                <!--<el-input v-model="consignment.transportMethod" placeholder="发运方式" size="small"></el-input>-->
                <!--</el-form-item>-->
                <el-form-item label="备注/Remark">
                    <el-input v-model="consignment.marks" size="small" type="textarea" placeholder="Remark"></el-input>
                </el-form-item>

                <div style="margin-bottom: 20px" v-if="urlAvailible('shanqi-contract-operate')">
                    <label for="file" class="label-btn">上传明细/Upload File</label>
                    <input type="file" @change="fileChange" id="file" v-show="false" ref="file">
                </div>
                <div class="table">
                    <el-table
                            :data="partList"
                            stripe
                            border
                            height="500px"
                            style="width:95%">
                        <el-table-column
                                prop="partsNumber"
                                label="配件编号/Part No"
                        >
                        </el-table-column>
                        <el-table-column
                                prop="denomination"
                                label="中文"
                                width="180">
                        </el-table-column>
                        <el-table-column
                                prop="designation"
                                label="English">
                        </el-table-column>
                        <el-table-column
                                prop="quantity"
                                label="数量/QTY">
                        </el-table-column>
                        <el-table-column
                                prop="unit"
                                label="单位/Unit">
                        </el-table-column>
                        <el-table-column
                                prop="salesUnitPrice"
                                label="单价/Price">
                            <template slot-scope="scope">
                                <span :class="scope.row.priceStatus === 1 ? 'warning':''">{{scope.row.salesUnitPrice}}</span>
                                <div v-if="scope.row.priceStatus === 1 ">Excel中单价与系统不一致</div>
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="totalPrice"
                                label="总价/Total Price">
                        </el-table-column>
                        <el-table-column
                                prop="remarks"
                                label="备注/Remarks">
                        </el-table-column>

                    </el-table>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">Cancel</el-button>
            <el-button type="primary" @click="submitForm"
                       v-if="urlAvailible('shanqi-contract-operate')">Confirm</el-button>
          </span>
        </el-dialog>
        <el-dialog
                title="Undelivered Part"
                :visible.sync="dialogVisible1"
                width="75%"
        >
            <el-table
                    height="600"
                    border
                    :data="unDeliveryList"
                    style="width: 100%">
                <el-table-column
                        prop="partsNumber"
                        label="配件编号/Part No"
                >
                </el-table-column>
                <el-table-column
                        prop="denomination"
                        label="中文"
                        width="180">
                </el-table-column>
                <el-table-column
                        prop="designation"
                        label="English">
                </el-table-column>
                <el-table-column
                        prop="unSendsQuantity"
                        label="数量/QTY">
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible1 = false">Close</el-button>
          </span>
        </el-dialog>
        <el-dialog
                :visible.sync="dialogVisible2"
                width="90%"
                >
            <el-table
                    :data="consignmentTimeList"
                    border
                    stripe
                    style="width: 100%">
                <el-table-column
                        prop="sendGoodsContract"
                        label="发运合同/Shipping Contract"
                       >
                </el-table-column>
                <el-table-column
                        prop="leaveFactoryDateStr"
                        label="出厂日期/Manufacture Date"
                       >
                </el-table-column>
                <el-table-column
                        prop="port"
                        label="出发港/Port"
                >
                </el-table-column>
                <el-table-column
                        prop="shipInformation"
                        label="船次/Ship Info">
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible2 = false">{{$t('cancel')}}</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
    import Crumb from '../../components/common/crumb'
    import {getContractList, addContract, modContract, contractFile, getContractDetail} from "../../api/contract";
    import {ERROR_OK} from "../../util/config";
    import {partList} from "../../store/getters";
    import authMixins from "../../util/authMixins"
    import {getConsignmentTime, getUndeliveryPart} from "../../api/shanxi";

    export default {
        name: "consignment",
        mixins: [authMixins],
        data() {
            return {
                consignmentList: [],
                consignmentTimeList:[],
                unDeliveryList: [],
                dialogVisible: false,
                dialogVisible1: false,
                dialogVisible2: false,
                consignment: {
                    contractNumber: '',
                    contractDateStr: '',
                    totalPrice: '',
                    customer: '',
                    marks: ''
                },
                key: '',
                total: 0,
                rule: {
                    contractNumber: [{required: true, message: '合同号必需填写'}],
                    contractDateStr: [{required: true, message: '日期必须选择'}]
                },
                partList: []
            }
        },
        created() {
            this.getConsignmentList()
        },
        methods: {
            async getConsignmentTime(row) {
                const {status ,data, msg} = await getConsignmentTime(row.id)
                if(status === ERROR_OK) {
                    this.consignmentTimeList = data
                    this.dialogVisible2 = true
                } else {
                    this.$message.error(msg)
                }
            },
            filterCustomer(value, row) {
                return row.customer === value;
            },
            filterStatus(value, row) {
                return row.remainingOrNot === value;
            },
            async showUnDelivery(row) {
                const {data, status} = await getUndeliveryPart(row.id);
                if (status === ERROR_OK) {
                    this.unDeliveryList = data;
                    this.dialogVisible1 = true
                }
            },
            async getPartDetail(row) {
                const target = this.consignmentList.find(item => {
                    return item.id === row.id
                });
                if (target) {
                    if (target.partList) {
                        return
                    }
                    const {status, data} = await getContractDetail(row.id);
                    if (status === ERROR_OK) {
                        const partList = data.map(item => {
                            return {
                                partsNumber: item.spareParts.partsNumber,
                                denomination: item.spareParts.denomination,
                                designation: item.spareParts.designation,
                                quantity: item.quantity,
                                unit: item.unit,
                                salesUnitPrice: item.salesUnitPrice,
                                partsId: item.spareParts.id,
                                totalPrice: item.totalLinePrice,
                                remarks: item.remarks
                            }
                        });
                        this.$set(target, 'partList', partList);
                    }


                }
            },
            async fileChange(e) {
                const formData = new FormData();
                Array.prototype.forEach.call(e.target.files, item => {
                    formData.append('exFiles', item);
                    formData.append('consignmentOrder', this.consignment.contractNumber);
                    formData.append('consignmentDateStr', this.consignment.contractDateStr);
                });
                const {status, data} = await contractFile(formData);
                if (status === 0) {
                    this.partList = data.data.notRepeatingConsignmentOrderList;
                    this.consignment.totalPrice = data.data.reallySparePartsPrice
                }
                this.$nextTick(() => {
                    this.$refs.file.value = '';
                })
            },
            openAdd() {
                this.dialogVisible = true;
                this.clear()
            },
            clear() {
                this.consignment = {
                    contractNumber: '',
                    contractDateStr: '',
                    customer: '',
                    marks: '',
                    totalPrice: '',
                    id: ''
                };
                this.partList = [];
            },
            async openEdit(row) {
                const {status, data} = await getContractDetail(row.id);
                if (status === ERROR_OK) {
                    this.partList = data.map(item => {
                        return {
                            partsNumber: item.spareParts.partsNumber,
                            denomination: item.spareParts.denomination,
                            designation: item.spareParts.designation,
                            quantity: item.quantity,
                            unit: item.unit,
                            salesUnitPrice: item.salesUnitPrice,
                            partsId: item.spareParts.id,
                            totalPrice: item.totalLinePrice,
                            remarks:item.remarks
                        }
                    });

                }
                this.consignment = row;
                this.dialogVisible = true
            },
            submitForm() {
                this.$refs.form.validate(async valid => {
                    if (valid) {
                        const {contractNumber, contractDateStr, customer, marks, id, totalPrice} = this.consignment;
                        if (!partList.length) {
                            this.$notify.error('合同必须有配件信息')
                        }
                        let consignmentOrderDetails = this.partList.map(item => {
                            return {
                                partsId: item.partsId,
                                quantity: item.quantity,
                                salesUnitPrice: item.salesUnitPrice,
                                unit: item.unit,
                                remarks: item.remarks,
                            }
                        });
                        consignmentOrderDetails = JSON.stringify(consignmentOrderDetails);
                        let belongModule = 1;
                        if (!customer) {
                            this.$message.error("Please Select Customer");
                            return
                        } else if (customer === 'WEDA') {
                            belongModule = 2
                        } else if (customer === 'MOROWALI') {
                            belongModule = 1
                        }
                        if (id) {
                            const {status, msg} = await modContract({
                                contractNumber,
                                contractDateStr,
                                customer,
                                marks,
                                consignmentOrderDetails,
                                id,
                                totalPrice,
                                transportMethod: '海运',
                                belongModule
                            });
                            if (status === 0) {
                                this.$notify.success('修改寄售合同成功');
                                this.clear();
                                this.dialogVisible = false
                            } else {
                                this.$notify.error(msg)
                            }
                        } else {
                            const {status, msg} = await addContract({
                                contractNumber,
                                contractDateStr,
                                customer,
                                marks,
                                belongModule,
                                consignmentOrderDetails,
                                totalPrice,
                                transportMethod: '海运'
                            });
                            if (status === ERROR_OK) {
                                this.$notify.success('增加寄售合同成功');
                                this.clear();
                                this.dialogVisible = false
                                this.getConsignmentList()
                            } else {
                                this.$notify.error(msg)
                            }
                        }

                    }
                })
            },
            async getConsignmentList() {
                const {status, data, msg} = await getContractList();
                if (status === ERROR_OK) {
                    this.consignmentList = data ? data : [];
                    this.total = msg
                } else {
                    this.consignmentList = [];
                    this.$notify.warning('没有寄售合同数据')
                }
            }
        },
        components: {
            Crumb
        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";

    .content {
        @include content
    }

    .label-btn {
        cursor: pointer;
        height: 30px;
        line-height: 30px;
        text-align: center;
        color: white;
        background-color: #409eff;
        border-radius: 3px;
        padding: 5px 15px;
        display: block;
        width: 120px;
    }

    .warning {
        color: #fff;
        font-weight: bold;
        background-color: #c60023;
    }
</style>